package com.vpen.iot.server;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.RSA;
import org.bouncycastle.util.io.pem.PemReader;

import java.io.FileReader;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPublicKey;


public class LicenseSigner {

    private final static String pk="-----BEGIN CERTIFICATE-----\n" +
            "MIIEujCCAqKgAwIBAgIJAOjggz5IQxdvMA0GCSqGSIb3DQEBCwUAMBgxFjAUBgNV\n" +
            "BAMMDUpldFByb2ZpbGUgQ0EwHhcNMjQxMTE1MDMzMjA4WhcNMzQxMTE0MDMzMjA4\n" +
            "WjAhMR8wHQYDVQQDDBZNb1l1bm8tZnJvbS0yMDIyLTA3LTI1MIICIjANBgkqhkiG\n" +
            "9w0BAQEFAAOCAg8AMIICCgKCAgEAsA+B3hCc5IsZD2AeUNCGtbqOkzmx3hES7RCf\n" +
            "Y5P6BoF+mYJviccknmvYg0g7gLf459eN2yuGMheEu30zpoBEwLwUA/RXYP3hQQHD\n" +
            "vIDws+bcWpzEff6lUMeIX49ruVQFVgZg/sXqfe9sQ+DhEoqu1m04zeAagDNVjYxo\n" +
            "aFkuncME7c5GsRkgRRkmkdjVdZsjOC152bsd8WL4eA6SR+Qp5YI0LTycCRQiv87B\n" +
            "hcmqIWbXA95xibPWnjiS74RIXUC2DxGFOcKJV3QgjTGnJO3EsddPQgnL/u8+4Iue\n" +
            "lxlU2uchwCCTHo3dEYwZ/+wEAMgn3UAXnfI7AaV1vCFgSkh0C9w7I8tM45gtyAKY\n" +
            "5EQi/3z950tI7vkjSmFye1TNxYKV6iG3mU5zIAjUvdfE1WVvZdoKJoHeL83+8GgK\n" +
            "gWQlX47nkFX7bKOqBpo878WwJSz/Fp5DM9pQYy/hJYt0rR6q7trlBQjcK7f/9sYL\n" +
            "c9SYNpnNm+/6Vx9/7Unqwq3Il23G+76pwHZXaweKhziyWF5wpXaaLU1GfrU5AZiy\n" +
            "KdzYPdgz38GYuhmqzXwprH/h+vCrehXVp0HhxcojTJAsh3u2GKzN8VS3+U0ZSfT6\n" +
            "a+uoFw1KK8xwcYQeORg3jrkixuGOq8dQ2NkG1VjQao7uHObB0+YQs3t/HDt4fZmR\n" +
            "mWlCT+sCAwEAATANBgkqhkiG9w0BAQsFAAOCAgEAXj6umwOHzrVMEuv6+n91wgiH\n" +
            "12+4bZbuWkeCb6+i8JEU58kwdJ5QrHkrrg98Yd8bJHtvJdN4+tz+ShUihAHEn9Dv\n" +
            "uRAXc/tCPw+bQymr3zEho0YHBLrozngo3Ctg9ba/9git7yoeBBKHDEgJeE5Vqo1Q\n" +
            "a3TtaOhOPJ8AL4RH+aKDjZvxxgNnNZ6T9wAQnyCBmAnFMGL5TSwfse5DEAj6qksM\n" +
            "w72mhIluz07DzP6Pks016rYTD7FfFXFOA7gdhBYx2tPMyQYQgLc/uI9BSWlYqy2X\n" +
            "2k8ZND3zRvkAE6094IwvbOqloWwTlikMZyItB/lsNN/Hqtm+2Sc6xm3SXSSUlAPP\n" +
            "erggYHCe/2HULSvt+FXosSVmt1QyoZ3rvx48Mh24E2Zwc+RohMFhhVt9Hcs+nX+6\n" +
            "deXdPRSu/IXKeUnbkE2QcpPgjnr3skHPr+IjkCVnPkJtvKi4grpqN5DjIvEpQrna\n" +
            "lGKBCaY3J7Nmv/74qaZ+oue7Q1nOv3VaDmNyPMPl2b0ux9NQCj2VX2digKDsBTbG\n" +
            "JiKUxm/9fNSRqgDqdWSrygWhs4BXHmXp2aB0EUgQS3S/0NOXbW41H7WqTT5Sfn7k\n" +
            "q009+pTjnlWBrq8niyqX46xJwgCIdhersSmAqBfHwiN1dh4n9RUEctJRCgfADIXr\n" +
            "e7NBqANohRUgmfIAOqQ=\n" +
            "-----END CERTIFICATE-----\n";
    private final static String ck="-----BEGIN RSA PRIVATE KEY-----\n" +
            "MIIJKQIBAAKCAgEAsA+B3hCc5IsZD2AeUNCGtbqOkzmx3hES7RCfY5P6BoF+mYJv\n" +
            "iccknmvYg0g7gLf459eN2yuGMheEu30zpoBEwLwUA/RXYP3hQQHDvIDws+bcWpzE\n" +
            "ff6lUMeIX49ruVQFVgZg/sXqfe9sQ+DhEoqu1m04zeAagDNVjYxoaFkuncME7c5G\n" +
            "sRkgRRkmkdjVdZsjOC152bsd8WL4eA6SR+Qp5YI0LTycCRQiv87BhcmqIWbXA95x\n" +
            "ibPWnjiS74RIXUC2DxGFOcKJV3QgjTGnJO3EsddPQgnL/u8+4IuelxlU2uchwCCT\n" +
            "Ho3dEYwZ/+wEAMgn3UAXnfI7AaV1vCFgSkh0C9w7I8tM45gtyAKY5EQi/3z950tI\n" +
            "7vkjSmFye1TNxYKV6iG3mU5zIAjUvdfE1WVvZdoKJoHeL83+8GgKgWQlX47nkFX7\n" +
            "bKOqBpo878WwJSz/Fp5DM9pQYy/hJYt0rR6q7trlBQjcK7f/9sYLc9SYNpnNm+/6\n" +
            "Vx9/7Unqwq3Il23G+76pwHZXaweKhziyWF5wpXaaLU1GfrU5AZiyKdzYPdgz38GY\n" +
            "uhmqzXwprH/h+vCrehXVp0HhxcojTJAsh3u2GKzN8VS3+U0ZSfT6a+uoFw1KK8xw\n" +
            "cYQeORg3jrkixuGOq8dQ2NkG1VjQao7uHObB0+YQs3t/HDt4fZmRmWlCT+sCAwEA\n" +
            "AQKCAgBd4Jbt0svlrSm6ohToIJiD1Crr4+qsr0v5LlDe5ut9hpT7w6o3vAERnA3B\n" +
            "ysU3mGFXNf/E6stOcG3tDxB4apK+dkrx5NqmtBjk8czt+Y7fTm0Wv9qiGCMMFKjp\n" +
            "026sTlneCd60WtHzPrPq6cD5gwtA+NI+LI3U6AppRIHzigIqSu+Y4dGd4vjq/0Mq\n" +
            "p4UChatc7Bq592U67fvxAEwNm2KfpzKtIFFPIfZ5cgSMkwBteQmTXYwK0eLRUPdA\n" +
            "UbfISZYKKNxx9QIIqLomr2Ahd8rWzSjM3K5yjB1p2+i/RtmRM4cyi+wGcbx7+8lt\n" +
            "RerIg/GFrwQoyx2dfh1uKBnQ4htFyTyWvwHDtK4Q9++9O8gSC8XULbAHqj7zJvFZ\n" +
            "DJhveSeG+O+Y31wJuACi9OkiBUzJd/4Y+geF3knsruKcIg6lmri9pO9I1o2sYj4I\n" +
            "6HfukT8AMTc8cuSxWqZUlmBskyRA7xS0Gzh6g6ATEA5x1uVr3XAOBu4upapC84XJ\n" +
            "0RFT2LvW0fFkuyw2TyDqRlD3IsZ5IPAo+5yj7agrWe9KdHijuCd+cGt7XnxZF6AY\n" +
            "plG1wNEqdNCHmn+A5uVd5jQWuVHzuveyzbNKvVhnhETR4pAJ+INMLbcnD9LXHBS7\n" +
            "osyH447oVWxU6xnH6OzjeQbYorSCMQURaHzhs7kVvwiu0oZ5gQKCAQEA2T0BwceN\n" +
            "2RX0zvfWZnI60N0+S9SqbSKsNcfkYnw5iRF7SYKBFg366CcB54dixxAjEnRC7HuY\n" +
            "jJtAvBY7sTdO3q2On4M/pBXC4vRVoMw7Pb7LCjnjG914TI8A0sapLaP9fdAzajiI\n" +
            "mv3MoX7GvhXNz/c6COHXUOdDWMEGpLqS5Wy9e2TmVoJi83uaO/eFONed2PmRvr08\n" +
            "86g5FhBZfs1MF+pxc0cdE6pDYfP6LzME2WEfGW9k4I40w3cZeMSwAxzj5HGou6Tc\n" +
            "QwESqkuDlo0Th7cUFSogU9Yl7RUqBtNMgH5ipYa99t2MrkOJUn5LtWI/d6OLS5fX\n" +
            "qtybM1VP4TxsqwKCAQEAz3mWYZK8Zkx6ZBlGzjsYYMo88iYkkzidA43QX7fsnp5q\n" +
            "qlu/NlCyukprKQHJdJoRFUG834LeemwYsDr1cKAxxrx5+bak/wEGFaqGY9tQJI6L\n" +
            "0uzbbXuvSGPPwGprrZCq0i/VwmKDRG58dFiAp4ssOEKAHypzVvHbtTBJ4sbCovoN\n" +
            "Krf41lcVOcUWCC+BvLeZ24zbnX+J9P3wBH3mZ7Rs3rd1w6RcHBsqHNac7Zlx5KIW\n" +
            "UGWrkFP1jDhQdNTk39JCVgJLj92NIlWokMvFIvJDhfI8K0L4i+9wxzJsnJ/4B9Re\n" +
            "Z1fR7/Nby8gXYbVGiJBe0To/M2GKlJag2sVpnecpwQKCAQEA1j+XywC/ghlobvL5\n" +
            "LeJ85V8+QFWGm8n1Y7k4InV33RozqGUgYJr7GRjXhPv+TGs628lz831WD15S8u1O\n" +
            "g9ITZARxxBoSmwanRWRKSyMBTj0sTHKY7PN44LCs1DP/yDaTHBFJk/obqBilR6Ub\n" +
            "537jk7a1MuthirX6sr70iWRE2iZrnhX+IdXIN3BwxbGxX0UvtT02I5LJWVlQq9UG\n" +
            "HsvkvzWGHHZHVAy5FhMkbIZ5wtZJcLFvIRS/LwP4SCZbnUZR8Ay0qBPI9ABL405E\n" +
            "giey2keSc+kvJt/uWatk3oRoT9XV/oAsPBt20qti9MwAaOxzwc+24p/noOif3HnI\n" +
            "JVCNrwKCAQBdR4QmAEv2DmJkiLy90fHm6mY2VJHTIvvs8iCCOHYI5p58U12HtQZ2\n" +
            "HSlKuYPyiaYukWyybOtLzTfYW9mntk5K1MheThCmmbY7nXxoftzsYq5Yuab59Ubc\n" +
            "XAu2reIVmdpDP8ByccokxSvtPzEworDR5owl9vb+WyT1tG0zqTsu/Q9YanhVHbfs\n" +
            "TkDWk01YJI/nFtBSYloLLPRxgI1LiOH9zCwFNus2s7veVVsetANx0LIJmXxmGmlm\n" +
            "jpcVv/Xa73RlqQiB+REQI8TyvLq4OIXFPiBxLt4CRDfHR1Nvo7hnBMMg4WoA4MAf\n" +
            "walJg6/fjFEk7nQlzK/6mDJfyavvk1PBAoIBAQDPJJb+FwsjU5dxbPHs19aoErT3\n" +
            "C8m3WXq9McfDuVW5eOpftzvlOWGXSowlQ6aQFTxmtZm+EOD+ochtAMBiMLt1vgN7\n" +
            "ah8hfK7UVNn4jFa5ni8YTxYEYujeQ/PIhUcJGFjAcx2TlWos8XvRaoRN7jCyU8Hs\n" +
            "HmRa68T+1fbDbJ5WIFHdXpj2AfFIJmtc8MrWjIY/Yt3lYvOwZrBq0CxYaIE/j8d2\n" +
            "U2etwTbBt1Wmu1NJFupUyMuLwcDkzzwbqDQ1kBYdKp0by/KSF7gTltn77h5PO/ho\n" +
            "UZxSii2lhJCHb7+mvBg/wArjDjUHo03yQPpTrkV4dOpHmuR1UcirZpMYDf6D\n" +
            "-----END RSA PRIVATE KEY-----\n";
    public static void main(String[] args) throws Exception {
        String licenseId = "12345";
        String licensePart = "someLicenseData";

        // 加载私钥
        PrivateKey privateKey = loadPrivateKey("ca.key");

        // 计算数据的 SHA-1 哈希值
        byte[] digest = getDigest(licensePart);

        // 使用私钥签名哈希值
        byte[] signature = signWithPrivateKey(privateKey, digest);

        // Base64 编码签名结果
        String sigResults =  java.util.Base64.getEncoder().encodeToString(signature);

        // Base64 编码许可部分
        String licensePartBase64 = java.util.Base64.getEncoder().encodeToString(licensePart.getBytes("UTF-8"));

        // 在这里模拟公钥验证过程（假设 public_key 是已加载的公钥）
        RSAPublicKey publicKey = loadPublicKey("ca.crt");
        verifySignature(publicKey, digest, signature);

        // 生成最终的结果
        String result = licenseId + "-" + licensePartBase64 + "-" + sigResults + "-" + "certificateBase64";
        System.out.println(result);
    }

    // 加载私钥
    public static PrivateKey loadPrivateKey(String filename) throws IOException, GeneralSecurityException {
//        SecureUtil
//        byte[] p = Base64.getDecoder().decode(pk);
//        byte[] c = Base64.getDecoder().decode(ck);


        RSA rsa = SecureUtil.rsa(ck, pk);
       return rsa.getPrivateKey();

//        PemReader pemReader = new PemReader(new FileReader(filename));
//        byte[] keyBytes = pemReader.readPemObject().getContent();
//
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//        return (RSAPrivateKey) keyFactory.generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(keyBytes));
//        return null;
    }

    // 加载公钥
    public static RSAPublicKey loadPublicKey(String filename) throws IOException, GeneralSecurityException {
        PemReader pemReader = new PemReader(new FileReader(filename));
        byte[] keyBytes = pemReader.readPemObject().getContent();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(new java.security.spec.X509EncodedKeySpec(keyBytes));
    }

    // 计算数据的 SHA-1 哈希值
    public static byte[] getDigest(String data) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        return digest.digest(data.getBytes());
    }

    // 使用私钥对哈希值签名
    public static byte[] signWithPrivateKey(PrivateKey privateKey, byte[] digest) throws SignatureException, NoSuchAlgorithmException {
        Signature signature = Signature.getInstance("SHA1withRSA");
        try {
            signature.initSign(privateKey);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        signature.update(digest);
        return signature.sign();
    }

    // 验证签名
    public static void verifySignature(RSAPublicKey publicKey, byte[] digest, byte[] signature) throws SignatureException {
        try {
            Signature verifier = Signature.getInstance("SHA1withRSA");
            verifier.initVerify(publicKey);
            verifier.update(digest);
            if (!verifier.verify(signature)) {
                throw new SignatureException("Signature verification failed");
            }
        } catch (Exception e) {
            throw new SignatureException("Signature verification failed", e);
        }
    }
}
